package com.fileBrowser.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.ListGridEditEvent;
import com.smartgwt.client.types.Overflow;
import com.smartgwt.client.widgets.Label;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.menu.Menu;
import com.smartgwt.client.widgets.menu.MenuItem;
import com.smartgwt.client.widgets.menu.events.MenuItemClickEvent;
import com.smartgwt.client.types.TreeModelType;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.events.DrawEvent;
import com.smartgwt.client.widgets.events.DrawHandler;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.events.CellClickEvent;
import com.smartgwt.client.widgets.grid.events.CellClickHandler;
import com.smartgwt.client.widgets.grid.events.CellDoubleClickEvent;
import com.smartgwt.client.widgets.grid.events.CellDoubleClickHandler;
import com.smartgwt.client.widgets.grid.events.CellSavedEvent;
import com.smartgwt.client.widgets.grid.events.CellSavedHandler;
import com.smartgwt.client.widgets.grid.events.RowContextClickEvent;
import com.smartgwt.client.widgets.grid.events.RowContextClickHandler;
import com.smartgwt.client.widgets.tree.Tree;
import com.smartgwt.client.widgets.tree.TreeGrid;
import com.smartgwt.client.widgets.tree.TreeGridField;
import com.smartgwt.client.widgets.tree.TreeNode;

public class FileBrowser implements EntryPoint {

	private final static GreetingServiceAsync greetingService = GWT.create(GreetingService.class);

	public void onModuleLoad() {

		/* ___TREE___ */

		final Tree employeeTree = new Tree();
		employeeTree.setModelType(TreeModelType.PARENT);
		employeeTree.setIdField("id");
		employeeTree.setParentIdField("Parent");  
		employeeTree.setNameProperty("Name");
		final FileTreeNode rootNode = new FileTreeNode("D:\\PRJ\\workspace\\FileBrowser\\war\\filebrowser\\FileBrowserRoot", "FileBrowserRoot");
		employeeTree.setRoot(rootNode);
		employeeTree.setDefaultIsFolder(true);

		final TreeGrid employeeTreeGrid = new TreeGrid();
		employeeTreeGrid.setHeight100();
		employeeTreeGrid.setWidth100();
		employeeTreeGrid.setShowOpenIcons(true);
		employeeTreeGrid.setShowDropIcons(true);
		employeeTreeGrid.setFields(new TreeGridField(""));
		employeeTreeGrid.setData(employeeTree);
		
		/* ___---===LISTGRID===---___ */
		
		final ListGrid filesGrid = new ListGrid();
		filesGrid.setWidth100();
		filesGrid.setHeight100();
		filesGrid.setShowAllRecords(true);
		filesGrid.setCanEdit(true);
		filesGrid.setEditEvent(ListGridEditEvent.NONE);
//		filesGrid.setEditByCell(true);

		filesGrid.setFields(new ListGridField("name", "Name"));

		employeeTreeGrid.addDrawHandler(new DrawHandler() {
			public void onDraw(DrawEvent event) {
				
				employeeTree.add(new FileTreeNode("D:\\PRJ\\workspace\\FileBrowser\\war\\filebrowser\\FileBrowserRoot", "FileBrowserRoot"), rootNode);

			}
		});
				
				employeeTreeGrid.addCellClickHandler(new CellClickHandler() {

					public void onCellClick(final CellClickEvent event) {
						
						greetingService.getSelected(event.getRecord().getAttributeAsString("id"),
								new AsyncCallback<FileManager>() {

									public void onFailure(Throwable caught) {
										SC.say("FAIL");
									}

									public void onSuccess(FileManager result) {
										open(result, employeeTree, filesGrid, event.getRecord().getAttributeAsString("Parent"), event.getRecord().getAttributeAsString("id"));
									}
								});
					}

				});
		
		filesGrid.addCellDoubleClickHandler(new CellDoubleClickHandler() {

			public void onCellDoubleClick(final CellDoubleClickEvent event) {
				
				greetingService.getSelected(event.getRecord().getAttributeAsString("id"),
						new AsyncCallback<FileManager>() {

							public void onFailure(Throwable caught) {
								SC.say("FAIL");
							}

							public void onSuccess(FileManager result) {		
								open(result, employeeTree, filesGrid, event.getRecord().getAttributeAsString("Parent"), event.getRecord().getAttributeAsString("id"));
							}
						});
			}
		});
		
//		employeeTreeGrid.addFolderDropHandler(new FolderDropHandler() {
//            public void onFolderDrop(FolderDropEvent event) {
//            	
//				greetingService.getSelected(event.getRecord().getAttributeAsString("id"),
//						new AsyncCallback<FileManager>() {
//
//							public void onFailure(Throwable caught) {
//								SC.say("Sheeeeeeeeeeit.");
//							}
//
//							public void onSuccess(FileManager result) {
//								open(result, employeeTree, filesGrid, event.getRecord().getAttributeAsString("Parent"), event.getRecord().getAttributeAsString("id"));
//							}
//						});
//            }
//        });
		
		filesGrid.addRowContextClickHandler(new RowContextClickHandler() {
			public void onRowContextClick(RowContextClickEvent event) {
				
				final String selectedFileID = event.getRecord().getAttributeAsString("id");
				final String selectedParent = event.getRecord().getAttributeAsString("Parent");
				
				final ListGridRecord selectedRecordID = event.getRecord();

				Menu contextMenu = new Menu();
				filesGrid.setContextMenu(contextMenu);
				final MenuItem renameItem = new MenuItem("Rename");
				final MenuItem deleteItem = new MenuItem("Delete");
				
				contextMenu.setItems(renameItem, deleteItem);

				renameItem.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler() {
							public void onClick(MenuItemClickEvent event) {
								
								filesGrid.startEditing(filesGrid.getRecordIndex(selectedRecordID));
								
								filesGrid.addCellSavedHandler(new CellSavedHandler(){

									public void onCellSaved(CellSavedEvent event) {
										
										final String parent = event.getRecord().getAttributeAsString("parent");
										final String renamed = event.getRecord().getAttributeAsString("name"); 

												greetingService
														.renameSelected(selectedFileID, parent, renamed, new AsyncCallback<FileManager>() {

																	public void onFailure(Throwable caught) {
																		SC.say("FAIL");
																	}

																	public void onSuccess(FileManager result) {
																		
																		greetingService.getSelected(result.getId(),
																				new AsyncCallback<FileManager>() {

																					public void onFailure(Throwable caught) {
																						SC.say("FAIL");
																					}

																					public void onSuccess(FileManager result) {		
//																						employeeTree.findById(selectedFileID).setID(result.getId());
																						open(result, employeeTree, filesGrid, result.getParent(), result.getId());
																					}
																				});
																	}
																});
									}
								});
							}
						});

				deleteItem.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler() {
							public void onClick(MenuItemClickEvent event) {
				
									greetingService.deleteSelected(selectedFileID, new AsyncCallback<FileManager>(){

										public void onFailure(Throwable caught) {
											SC.say("FAIL");
										}
												public void onSuccess(FileManager result) {
													
												if (employeeTree.findById(selectedFileID) != null) {
													employeeTree.remove(employeeTree.findById(selectedFileID));
												}
												filesGrid.removeData(selectedRecordID);
												}
									});
								}
						});
			}
		});

		/* ___LAYOUT___ */

		HLayout mainLayout = new HLayout();
		mainLayout.setWidth100();
		mainLayout.setHeight100();

		Label navigationLabel = new Label();
		navigationLabel.setContents("Navigation");
		navigationLabel.setAlign(Alignment.CENTER);
		navigationLabel.setWidth("20%");
		navigationLabel.setShowResizeBar(true);
		navigationLabel.addChild(employeeTreeGrid);
		
		mainLayout.addMember(navigationLabel);

		VLayout vLayout = new VLayout();
		vLayout.setWidth("70%");

		Label listingLabel = new Label();
		listingLabel.setContents("Listing");
		listingLabel.setAlign(Alignment.CENTER);
		listingLabel.setOverflow(Overflow.HIDDEN);
		listingLabel.setHeight("80%");
		listingLabel.setShowResizeBar(true);
		listingLabel.addChild(filesGrid);

		Label detailsLabel = new Label();
		detailsLabel.setContents("Details");
		detailsLabel.setAlign(Alignment.CENTER);
		detailsLabel.setOverflow(Overflow.HIDDEN);
		detailsLabel.setHeight("20%");

		vLayout.addMember(listingLabel);
		vLayout.addMember(detailsLabel);

		mainLayout.addMember(vLayout);
		mainLayout.draw();

	}
	
	public static void open(FileManager result, Tree employeeTree,
			ListGrid filesGrid, String parent, String id) {

		if (!result.getChildren().isEmpty()) {

			filesGrid.selectAllRecords();
			filesGrid.removeSelectedData();

			for (int i = 0; i < result.getChildren().size(); i++) {

				FileTreeNode child = new FileTreeNode(result.getChildren().get(i).getId(), parent, result.getChildren().get(i).getName());

				if (result.getChildren().get(i).getIsDir() == true) {

					employeeTree.add(child, employeeTree.findById(id));

					ListGridRecord record = new ListGridRecord();
					record.setAttribute("name", result.getChildren().get(i).getName());
					record.setAttribute("id", result.getChildren().get(i).getId());
					record.setAttribute("parent", result.getChildren().get(i).getParent());
					filesGrid.addData(record);

				} else {
					ListGridRecord record = new ListGridRecord();
					record.setAttribute("name", result.getChildren().get(i).getName());
					record.setAttribute("id", result.getChildren().get(i).getId());
					record.setAttribute("parent", result.getChildren().get(i).getParent());
					filesGrid.addData(record);
				}
			}
		}
		employeeTree.openFolder(employeeTree.findById(id));
	}

	public static class FileTreeNode extends TreeNode {
		
		public FileTreeNode(String id, String name) {  
            setAttribute("id", id);  
            setAttribute("Name", name);  
        }  

		public FileTreeNode(String id, String parent, String name) {  
            setAttribute("id", id);  
            setAttribute("Parent", parent);  
            setAttribute("Name", name);  
        }  
	}
}
